<template>
    <div id="allmap">

    </div>
</template>

<script setup lang="ts">
    /* 引入hook */
    import { useBaiduMap } from "@/hooks";
    /* 引入vue函数 */
    import {
        onMounted,
        reactive,
    } from 'vue';
    /* 引入接口定义 */
    import { IPositionInfo } from "@/components/my-baidu-map/extends";
    /* 解构hook方法 */
    const {
        initMap,
        addController,
        addEventControl
    } = useBaiduMap();
    /* 逆解析器对象 */
    let geocoder: any;
    /* 位置信息对象 */
    const positionInfo: IPositionInfo = reactive({
        lat: undefined,
        lng: undefined,
        province: undefined,
        city: undefined
    })
    /* 给位置对象赋值的函数 */
    const setProvinceInfo = (point: PointerEvent): void => {

        if (!point) {
            return;
        }
        geocoder.getLocation(point, function (rs: any) {
            // 获取地理信息组件
            const addressComp = rs.addressComponents;
            positionInfo.province = addressComp.province;
            positionInfo.city = addressComp.city;
        })

    };

    onMounted(async () => {
        // 初始化地图
        initMap('allmap');
        // 添加缩放控件
        addController('ScaleControl', {
            anchor: 'BMAP_ANCHOR_BOTTOM_LEFT'
        });
        // 添加城市列表控件
        addController('CityListControl', {
            anchor: 'BMAP_ANCHOR_TOP_RIGHT',
            onChangeSuccess(ev: any) {
                if (!geocoder) {
                    geocoder = reactive(new window.BMap.Geocoder({ extensions_town: true }));
                }
                setProvinceInfo(ev.point);
            }
        });
        // 添加事件
        addEventControl('click', (e: any, map: any) => {
            const { point: { lng, lat } } = e;
            const Point = new window.BMap.Point(lng, lat),
                marker = new window.BMap.Marker(Point);
            positionInfo.lng = lng;
            positionInfo.lat = lat;
            // 清除地图标记
            map.clearOverlays();
            // 添加地图标记
            map.addOverlay(marker);
            // 添加标记跳动动画
            marker.setAnimation(window.BMAP_ANIMATION_BOUNCE);
        })
    });

    // 暴露positionInfo 提供给父级组件访问
    defineExpose({ positionInfo })
</script>

<style scoped>
    #allmap {
        width: 100%;
        height: 100%;
    }

</style>
